<?php
namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use app\common\model\Cars;
use app\common\model\CarFile;

class Files extends Command
{
    protected function configure()
    {
        $this
            ->setName('files')->setDescription('文件操作脚本')
            ->addOption('path', 'd', Option::VALUE_OPTIONAL, 'path to upload', null);
    }

    protected function execute(Input $input, Output $output)
    {
        $num = 0;
        $path = $input->getOption('path') ?: '';
        $res = $this->forFile($path);
        foreach ($res as $key => $value) {
            // var_dump($value);//完整的路径
            $model = $this->updateFile($value);
            if($model){
                $num++;
            }
        }
        $output->writeln('添加了'.$num.'条数据');
    }
    protected function updateFile($path)
    {
        $pathinfo = pathinfo($path);
        $model = Cars::where('car_sn','like','%'.$pathinfo['filename'].'%')->find();
        if($model){

            $data['file_url'] = '20180102/'.md5($path).'.'.$pathinfo['extension'];
            copy($path,$data['file_url']);
            $data['car_id'] = $model->car_id;
            $data['file_type'] = 1;
            
            $carFile = CarFile::create($data);
            if($carFile->id){
                return true;
                
            }else{
                return false;
            }
        }


    }

    // 使用生成器返回file数据
    protected function forFile($path)
    {
        if($path){
            $flies = scandir($path);
            foreach ($flies as $key => $file) {
                if('.' != $file && '..' != $file){
                    if (is_dir($path .'/'. $file)) {
                        
                    }else{
                        yield $path .'/'. $file;
                                            
                    }
                }
                
            }
        }
    }
}